/*
 * @lc app=leetcode.cn id=757 lang=typescript
 *
 * [757] 设置交集大小至少为2
 */

// @lc code=start
function intersectionSizeTwo(intervals: number[][]): number {
  intervals.sort((a, b) => {
    if (a[0] === b[0]) {
      return b[1] - a[1];
    }
    return a[0] - b[0];
  });

  const n = intervals.length;
  let ans = 2;
  let l = intervals[n - 1][0];
  let r = l + 1;
  for (let i = n - 2; i >= 0; i--) {
    const [lt, rt] = intervals[i];
    if (rt >= l && rt < r) {
      ans++;
      r = l;
      l = lt;
    } else if (rt < l) {
      ans += 2;
      l = lt;
      r = l + 1;
    }
  }

  return ans;
}
// @lc code=end
